package com.muye.dianli.activity;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.mime.content.StringBody;

import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.google.gson.Gson;
import com.muye.constant.C;
import com.muye.constant.U;
import com.muye.dianli.BaseActivity;
import com.muye.dianli.R;
import com.muye.field.ContactData;
import com.zvezda.algorithm.utils.MD5;
import com.zvezda.http.utils.HttpConst;
import com.zvezda.http.utils.KeyValue;
import com.zvezda.http.utils.RequestHttpListener;
import com.zvezda.http.utils.RequestHttpPostThread;

/**
 * 地图页面
 * 
 * @author TangChao
 *
 */
public class MapActivity extends BaseActivity implements OnClickListener, OnKeyListener
{
	/**
	 * 请求数据线程
	 */
	private RequestHttpPostThread requestHttpPostThread;
	
	/**
	 * 地图对象
	 */
	private MapView mapView;
	
	/**
	 * 弹出层
	 */
	private PopupOverlay popupOverlay;
	
	/**
	 * 弹出层对象
	 */
	private PopOverlay mPopOverlay;
	
	/**
	 * 地图管理对象
	 */
	private BMapManager bMapManager;
	
	/**
	 * 地图控制对象
	 */
	private MapController mapController;
	
	/**
	 * 气泡上的说明框
	 */
	private View view;
	
	/**
	 * 数据源
	 */
	private List<ContactData> arrayList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getWindow().setFormat(PixelFormat.RGBA_8888);
		bMapManager = new BMapManager(getApplication());
		bMapManager.init(null);
		setContentView(R.layout.map_layout);
		createTitle();
		mapView = (MapView) findViewById(R.id.map_layout_map_view);
		mapView.setBuiltInZoomControls(true);
		mapController = mapView.getController();
		// mapController.setCenter(new GeoPoint((int) (39.954524 * 1E6), (int) (116.461445 * 1E6)));
		getContactUs();
	}
	
	@Override
	protected void onDestroy()
	{
		mapView.destroy();
		if (bMapManager != null)
		{
			bMapManager = null;
		}
		super.onDestroy();
	}
	
	@Override
	protected void onPause()
	{
		mapView.onPause();
		if (bMapManager != null)
		{
			bMapManager.stop();
		}
		super.onPause();
	}
	
	@Override
	protected void onResume()
	{
		mapView.onResume();
		if (bMapManager != null)
		{
			bMapManager.start();
		}
		super.onResume();
	}
	
	/**
	 * 初始化标题栏
	 */
	private void createTitle()
	{
		TextView titleName = (TextView) findViewById(R.id.title_bar_name_text_view);
		titleName.setText("商家地图");
		titleName.setTextColor(getResources().getColor(R.color.black));
		ImageView titleLeftBtn = (ImageView) findViewById(R.id.title_bar_left_image_view);
		titleLeftBtn.setVisibility(View.VISIBLE);
		titleLeftBtn.setImageResource(R.drawable.title_back_icon_map);
		titleLeftBtn.setOnClickListener(this);
	}
	
	/**
	 * 请求联系我们
	 */
	private void getContactUs()
	{
		C.openPragressDialog(this, this, R.string.in_request_data);
		ArrayList<KeyValue<String, Object>> paramsList = new ArrayList<KeyValue<String, Object>>();
		String str = C.APPID + C.CONSTANT;
		try
		{
			paramsList.add(new KeyValue<String, Object>("appId", new StringBody(C.APPID, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("sign", new StringBody(MD5.getMD5_32(str), Charset.forName("utf-8"))));
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		requestHttpPostThread = new RequestHttpPostThread(getContactUsListenr, U.GET_CONTACT_US, paramsList);
		requestHttpPostThread.start();
	}
	
	/**
	 * 请求联系我们返回监听
	 */
	private RequestHttpListener getContactUsListenr = new RequestHttpListener()
	{
		
		@Override
		public void requestHttp(Message msg)
		{
			Bundle bundle = msg.getData();
			int result = bundle.getInt(HttpConst.ACTION_RESULT, HttpConst.ACTION_FAIL);
			if (result == HttpConst.ACTION_SUCCESS)
			{
				byte[] dataArr = bundle.getByteArray(HttpConst.DATA_ARR);
				try
				{
					String str = new String(dataArr, "utf-8");
					Log.i(C.TAG, "请求联系我们结果----->" + str);
					Gson gson = new Gson();
					ContactField item = gson.fromJson(str, ContactField.class);
					arrayList = item.data;
				}
				catch (UnsupportedEncodingException e)
				{
					e.printStackTrace();
				}
				Message message = new Message();
				message.what = 0;
				message.arg1 = result;
				handler.sendMessage(message);
			}
		}
	};
	
	/**
	 * 处理数据
	 */
	private Handler handler = new Handler()
	{
		
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			C.closePragressDialog();
			switch (msg.what)
			{
				case 0:
					switch (msg.arg1)
					{
						case HttpConst.ACTION_SUCCESS:
							double latitude = Double.parseDouble(arrayList.get(0).latitude);
							double longitude = Double.parseDouble(arrayList.get(0).longitude);
							GeoPoint geoPoint = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6));
							mapController.setCenter(geoPoint);
							mapController.setZoom(14);
							initOverlay();
							break;
						case HttpConst.ACTION_FAIL:
							C.showToast(MapActivity.this, "请求失败,请重试");
							mapController.setCenter(new GeoPoint((int) (39.954524 * 1E6), (int) (116.461445 * 1E6)));
							break;
						
						default:
							break;
					}
					break;
				
				default:
					break;
			}
		}
		
	};
	
	/**
	 * 载入层
	 */
	private void initOverlay()
	{
		view = getLayoutInflater().inflate(R.layout.map_pop_view_layout, null);
		mPopOverlay = new PopOverlay(getResources().getDrawable(R.drawable.position), mapView);
		/* ===================================== */
		for (int i = 0; i < arrayList.size(); i++)
		{
			GeoPoint geoPoint = new GeoPoint((int) (Double.parseDouble(arrayList.get(i).latitude) * 1E6),
					(int) (Double.parseDouble(arrayList.get(i).longitude) * 1E6));
			OverlayItem shopOverlayItem = new OverlayItem(geoPoint, arrayList.get(i).desc, "");
			shopOverlayItem.setMarker(getResources().getDrawable(R.drawable.position));
			mPopOverlay.addItem(shopOverlayItem);
		}
		/**
		 * 将overlay 添加至MapView中
		 */
		mapView.getOverlays().add(mPopOverlay);
		popupOverlay = new PopupOverlay(mapView, popupClickListener);
		mapView.refresh();
	}
	
	/**
	 * 弹出层点击事件
	 */
	private PopupClickListener popupClickListener = new PopupClickListener()
	{
		
		@Override
		public void onClickedPopup(int arg0)
		{
		}
	};
	
	public class PopOverlay extends ItemizedOverlay<OverlayItem>
	{
		public PopOverlay(Drawable defaultMarker, MapView mapView)
		{
			super(defaultMarker, mapView);
		}
		
		@Override
		public boolean onTap(int index)
		{
			GeoPoint geoPoint = new GeoPoint((int) (Double.parseDouble(arrayList.get(index).latitude) * 1E6),
					(int) (Double.parseDouble(arrayList.get(index).longitude) * 1E6));
			TextView nameText = (TextView) view.findViewById(R.id.nameView);
			nameText.setText(arrayList.get(index).desc);
			nameText.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					// Intent intent = new Intent();
					// intent.setClass(MapActivity.this, LoginActivity.class);
					// startActivity(intent);
					C.showToast(MapActivity.this, "您点击了窗口");
				}
			});
			popupOverlay.showPopup(view, geoPoint, 32);
			return true;
		}
		
		@Override
		public boolean onTap(GeoPoint pt, MapView mMapView)
		{
			if (popupOverlay != null)
			{
				popupOverlay.hidePop();
				mMapView.removeView(view);
			}
			return false;
		}
	}
	
	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
			case R.id.title_bar_left_image_view:
				finish();
				break;
			
			default:
				break;
		}
	}
	
	@Override
	public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
	{
		if (requestHttpPostThread != null)
		{
			requestHttpPostThread.interrupt();
			requestHttpPostThread.setRequestHttpListener(null);
		}
		return false;
	}
	
}
